//
// Created by sjjmw on 2/22/2022.
//
#include "iostream"
#include "vector"
struct Sol{
    std::vector<std::vector<int>> mat;
    bool first= true;
    void print(int i){
        if(!first){
            printf(" ");
        }
        first=false;
        printf("%d", i);
    }
    //m行 n列
    void run(int m,int n){
        std::vector<int> line(n);
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                std::cin>>line[j];
            }
            mat.push_back(line);
        }
        int x=0,y=0;
        int dir=0;//0 d, 1 r , 2 u , 3 l
        int m_n=m*n;
        for(int i=0;i<m_n;i++){
            switch (dir) {
                case 0: {
                    print(mat[y][x]);
                    mat[y][x]=-1;
                    y++;
                    if (y >= m || mat[y][x] == -1) {
                        dir++;
                        y--;x++;
                    }
                }
                break;
                case 1:
                {
                    print(mat[y][x]);
                    mat[y][x]=-1;
                    x++;
                    if (x >= n || mat[y][x] == -1) {
                        dir++;
                        x--;y--;
                    }
                }
                break;
                case 2:
                {
                    print(mat[y][x]);
                    mat[y][x]=-1;
                    y--;
                    if (y <0 || mat[y][x] == -1) {
                        dir++;
                        y++;
                        x--;
                    }
                }
                break;
                case 3:
                {
                    print(mat[y][x]);
                    mat[y][x]=-1;
                    x--;
                    if (x <0 || mat[y][x] == -1) {
                        dir=0;
                        x++;
                        y++;
                    }
                }
                break;
            }
        }
    }
};
int main() {
    int a,b;
    while (std::cin>>a>>b){
        Sol().run(a,b);
    }
    return 0;
}
